import $ from '../common/jq.style'
import {extend} from '../common/Tool'

/**
 *
 * ## 结构
 * 控件 <div class=${actSheetCls}> <-kt-actionsheet
 *     上部分按钮： <div class=${actBtnCls}"> <- kt-actionsheet-btn
 *         标题：   <div class="${actTitleCls actBtnItemCls fontCls}">${title}</div> <- kt-actionsheet-title kt-border-b kt-font-size-12
 *         按钮：   [<div class="${actBtnItemCls borderButtomCls}">${buttons[i].title}</div>*] //多个button <-kt-actionsheet-btn-item kt-border-b
 *  最后一个按钮:    <div class="${actBtnItemCls}">${buttons[i].title}</div>     //最后一个button <- kt-actionsheet-btn-item
 *                </div>
 *      下部分按钮：<div class=${actBtnCls}"> <- kt-actionsheet-btn>
 *                  <div class="${actBtnItemCls}">${oktitle}</div>
 *                  <div class="${actBtnItemCls}">${canceltitle}</div>
 *               </div>
 *     <div>
 *
 *
 * ## 用法
 * import createActionsheet from '../../component/actionsheet'
 *
 * const actionsheet = createActionsheet()
 *
 * const buttons = (function (amt) {
 *  const ret = [] for (let i=0;i<amt;++i) {
 *    ret.push({title: '按钮'+i})
 *  }
 *  return ret }
 * )(100）
 *
 * actionsheet.init({
 *  okTitle:'确定',
 *  buttons
 *  }, (selectButtons)=>{
 *  alert(JSON.stringify(selectButtons))
 *  })
 *
 */
class ActionSheet {
  init(options, callback) {
    extend(this, {
      frameBounces: false, //frame是否弹动

      title: false, //标题：放置到顶部
      okTitle: false, //确定按钮标题
      cancelTitle: '取消',

      maskDiv: false, //遮罩的div
      actionsheetDiv: false, //控件的div
      buttons: [], //控件按钮

      actSheetCls: 'kt-actionsheet',
      actTitleCls: 'kt-actionsheet-title',
      actBtnCls: 'kt-actionsheet-btn',
      actBtnItemCls: 'kt-actionsheet-btn-item',

      maskDivCls: 'kt-mask',
      maskInCls: 'kt-mask-in',
      fontCls: 'kt-font-size-12',
      borderTopCls: 'kt-border-t',
      borderButtomCls: 'kt-border-b',
      selectedCls: 'kt-selected',

    }, options)

    this._open(options, callback)
  }

  _open(options, callback) {
    const self = this
    if (self.actionsheetDiv || ( !self.title && !self.buttons && !self.cancelTitle && !self.destructiveTitle )) {
      return
    }

    //创建遮罩宿主-div
    if (!self.maskDiv) {
      self.maskDiv = document.createElement('div')
      self.maskDiv.className = self.maskDivCls
      document.body.appendChild(self.maskDiv)
    }
    //创建actionsheet控件宿主-div
    self.actionsheetDiv = document.createElement('div')
    self.actionsheetDiv.className = self.actSheetCls
    document.body.appendChild(self.actionsheetDiv)

    //创建内部按钮：分上部分和下部分
    const titleHtml = _createTitleHtml(self) //创建标题按钮
    const buttonsHtml = _createButtonsHtml(self) //创建点选的按钮
    const topHtml = _creteButtonsHtmlDiv(self, titleHtml, buttonsHtml) //创建上半部分的按钮

    const okHtml = _createOkHtml(self)
    const cancelHtml = _createCancelHtml(self)
    const bottomHtml = _creteButtonsHtmlDiv(self, okHtml, cancelHtml) //创建下半部分的按钮

    //建立dom，设置style
    self.actionsheetDiv.insertAdjacentHTML('beforeend', topHtml + bottomHtml)
    self.actionsheetDiv.style.webkitTransform = self.actionsheetDiv.style.transform = 'translate3d(0,0,0)'
    self.actionsheetDiv.style.opacity = 1
    self.actionsheetDiv.addEventListener('touchmove', (event) => {
      //event.preventDefault()
    })

    self.maskDiv.classList.add(self.maskInCls)
    self.maskDiv.addEventListener('touchmove', (event) => {
      event.preventDefault()
    })

    if (self._frameBounces()) {
      api.setFrameAttr({
        bounces: false
      })
    }

    //绑定事件
    this._bindEvent(callback)

  }

  _bindEvent(callback) {
    const self = this
    const multi = !!self.okTitle //如果设置了确定按钮，则表明是多选
    //装置事件
    const $actionsheet = $(self.actionsheetDiv)
    const $actionsheetButtons = $actionsheet.find(`.${self.actBtnItemCls}`)
    setTimeout(() => {
      self.maskDiv.onclick = function () {
        self._close()

      }
      $actionsheetButtons.each(function () {
        this.onclick = function () {
          const $e = $(this)
          if ($e.hasClass('j_cancel')) {
            self._close()
          }
          else if ($e.hasClass('j_ok')) {
            const $selectedItems = $actionsheet.find(`.${self.selectedCls}`)
            const selectedButtons = []
            $selectedItems.each(function () {
              const idx = $(this).attr('data-idx')
              selectedButtons.push(self.buttons[+idx])
            })
            if (selectedButtons.length > 0) {
              if (callback) callback(selectedButtons)
              self._close()
            }
          }
          else if ($e.hasClass('j_btn')) {
            if (multi) {
              $e.toggleClass(self.selectedCls)
            }
            else {
              const idx = $e.attr('data-idx')
              if (callback) callback([self.buttons[+idx]])
              self._close()
            }
          }
        }
      })
    }, 350)
  }

  _close() {
    const self = this
    if (self._frameBounces()) {
      api.setFrameAttr({
        bounces: true
      })
    }
    if (self.actionsheetDiv) {
      const actionsheetHeight = self.actionsheetDiv.offsetHeight
      self.actionsheetDiv.style.webkitTransform = self.actionsheetDiv.style.transform = `translate3d(0,${actionsheetHeight}px,0)`
      self.maskDiv.style.opacity = 0
      setTimeout(() => {
        self.maskDiv.parentNode.removeChild(self.maskDiv)
        self.actionsheetDiv.parentNode.removeChild(self.actionsheetDiv)
        self.actionsheetDiv = self.maskDiv = false
      }, 300)
    }
  }

  _frameBounces() {
    return typeof ( api ) !== 'undefined' && typeof ( api ) === 'object' && this.frameBounces
  }
}


function _createTitleHtml(self) {
  let titleHtml = ''
  if (self.title) {
    titleHtml = `<div class="${self.actTitleCls} ${self.borderTopCls} ${self.fontCls}">${self.title}</div>`
  }
  return titleHtml
}

function _createButtonsHtml(self) {
  let buttonsHtml = ''
  const buttons = self.buttons
  if (buttons.length) {
    for (let i = 0, len = buttons.length; i < len; i++) {
      if (i === buttons.length - 1) {
        buttonsHtml += `<div class="${self.actBtnItemCls}  j_btn" data-idx="${i}">${self.buttons[i].title}</div>`
      } else {
        buttonsHtml += `<div class="${self.actBtnItemCls} ${self.borderButtomCls} j_btn" data-idx="${i}">${self.buttons[i].title}</div>`
      }
    }
  }
  return buttonsHtml
}

function _createCancelHtml(self) {
  return `<div class="${self.actBtnItemCls} j_cancel">${self.cancelTitle}</div>`
}

function _createOkHtml(self) {
  let okHtml = ''
  if (self.okTitle) {
    okHtml = `<div class="${self.actBtnItemCls} ${self.borderButtomCls} j_ok">${self.okTitle}</div>`
  }
  return okHtml
}

function _creteButtonsHtmlDiv(self, btnHtml1, btnHtml2) {
  let btnHtml = ''
  if (btnHtml1 !== '' || btnHtml2 !== '') {
    btnHtml = `<div class="${self.actBtnCls}">${btnHtml1}${btnHtml2}</div>`
  }
  return btnHtml
}

export default function () {
  return new ActionSheet()
}
